package com.example.browser.happylook;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.browser.DownloadImage;
import com.example.browser.R;
import com.example.browser.happylook.adapter.MainAdapter;
import com.example.browser.happylook.bean.Pictures;
import com.example.browser.webview;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


//出处 https://blog.csdn.net/qq_40642784/article/details/118107186
// http加载错误解决方法 https://blog.csdn.net/weixin_42446378/article/details/91873102
public class PicView extends Activity implements MainAdapter.ItemClickListener {

    public static String TAG = "qzh";
    private long mExitTime;  //存在时间，初值为0，用于和当前时间（毫秒数）做差值
    private SpinKitView loadView;
    private RecyclerView recyclerView;
    private MainAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picview);
        initView();
        Intent it=super.getIntent();
        String htmlData=it.getStringExtra("htmlData");
        Tools.initData(htmlData,0);
//        new Thread(new Runnable(){
//            public void run(){
//                //获取服务端的url
//                try {
//
//                    String htmlString=CodeHtml.GetHtml("https://699pic.com/photo/", "utf-8");
//                    String code=CodeHtml.getURLCode("http://m.acg456.com/b/DJR/0/074/","utf-8");
//                    System.out.println("a啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"+code);
//
//                }catch(Exception e){
//                    System.err.println("错误");
//
//                }
//            }
//        }).start();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this);
        }
    }

    @SuppressLint("WrongViewCast")
    public void initView(){
        recyclerView = findViewById(R.id.main_recycler);

        loadView = findViewById(R.id.load_view);
        GridLayoutManager layoutManager = new GridLayoutManager(this,1);//这里是设置一行几个
        recyclerView.setLayoutManager(layoutManager);
        adapter = new MainAdapter(this ,this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleMessage(@NonNull Message msg) {
        switch (msg.what){
            case 10086:
                loadView.setVisibility(View.INVISIBLE);
                adapter.setList((List<Pictures>)msg.obj);
                recyclerView.setAdapter(adapter);
                break;
            case 1008613:
                Toast.makeText(this, "出现错误！！", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    //退出程序提示
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {  //mExitTime的初始值为0，currentTimeMillis()肯定大于2000（毫秒），所以第一次按返回键的时候一定会进入此判断
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();

            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void clickListener(View v, String categoryName, String moreUrl) {
        new AlertDialog.Builder(PicView.this)
                .setItems(new String[]{"保存图片到本地"}, (dialog, which) -> {

                    switch (which) {
                        case 0:
                            String root = Environment.getExternalStorageDirectory().getAbsolutePath();
                            String newPath="/yunxi/downloadpic";
                            Toast.makeText(this,moreUrl, Toast.LENGTH_SHORT).show();
                            //文件名为时间
                            long timeStamp = System.currentTimeMillis();
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
                            String sd = sdf.format(new Date(timeStamp));
                            String fileName = sd + ".png";
                            File mFile = new File(root+newPath,fileName);
                            //https://www.jianshu.com/p/4f457a124d67
                            DownloadImage downloadImage = new DownloadImage(moreUrl, getApplicationContext(),0,0, mFile, new DownloadImage.ImagedownLoadCallBack() {
                                @Override
                                public void onDownLoadSuccess(Bitmap bitmap) {
                                    Toast.makeText(PicView.this, "下载完成,图片保存在"+root+newPath, Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri uri = Uri.fromFile(mFile);
                                    intent.setData(uri);
                                    sendBroadcast(intent);
                                }
                                @Override
                                public void onDownLoadFailed() {
                                    Toast.makeText(PicView.this, "下载失败", Toast.LENGTH_SHORT).show();
                                }
                            });
                            new Thread(downloadImage).start();//异步下载

                            break;
                    }
                })
                .show();

    }
}